package com.rp.system.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.exception.UsernameExistException;
import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.controller.RpController;
import com.rp.system.po.Organ;
import com.rp.system.po.User;
import com.rp.system.service.LoginLogService;
import com.rp.system.service.OrganService;
import com.rp.system.service.UserService;

@Controller
@RequestMapping("/rp/")
public class MainController extends RpController{
	
	@Autowired
	private LoginLogService loginLogService;
	@Autowired
	private OrganService organService;
	@Autowired
	private UserService userService;

	@RequestMapping("login")
	public ModelAndView login(String error){
		if(error != null){
			model.put("errorMsg", session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION").toString());
		}
		return forward("/rp/login.jsp");
	}
	
	@ResponseBody
	@RequestMapping("registerUser")
	public String registerUser(String json){
		
		Map<String, Object> map = JsonUtil.jsonToMap(json);
		
		User user = new User();
		user.setUsername((String)map.get("username"));
		user.setPassword((String)map.get("password"));
		user.setRealname((String)map.get("realname"));
		
		if(!RpUtil.isNullOrEmpty((String)map.get("organId"))){
			Organ organ = organService.getOrganDao().get((String)map.get("organId"));
			user.setOrganId(organ.getId());
			user.setOrganName(organ.getName());
		}
		
		user.setRemark((String) map.get("remark"));
		user.setEnabled2("0");
		try {
			userService.registerUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		
		return SUCCESS;
	}
	
	@RequestMapping("index")
	public ModelAndView index(){
		//System.out.println("访问系统首页");
		model.put("webpageTitle", "RaptorPlatform2");
		return forward("/rp/index.jsp");
	}
	
	/**
	 * 成功登录系统首页之后，保存登录日志（弃用）
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveLoginLog")
	public String saveLoginLog(){
		User user = User.getCurrentUser();
		if(user != null){
			loginLogService.addLoginLog(
					request.getRemoteAddr(), 
					user.getUsername(), 
					user.getRealname());
		}
		return SUCCESS;
	}
	
}
